package com.erbao;

import com.erbao.io.netty.refactor.rpc.protocol.MyContent;
import io.netty.buffer.ByteBuf;

import java.io.*;

/**
 * @author CaoBaoYin
 * @since 2023/3/1 21:00
 */
public class IoUtil {
    static ByteArrayOutputStream baos = new ByteArrayOutputStream();
    public synchronized static byte[] serialize (Object obj) {
        baos.reset();

        byte[] msgBodyBytes = null;
        try (ObjectOutputStream oos = new ObjectOutputStream(baos);){
            //分析此处的嵌套，装饰模式（里面的对象先执行，外面的对象先调用）
            oos.writeObject(obj);
            msgBodyBytes = baos.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        return msgBodyBytes;
    }


    public static MyContent getContent(ByteBuf content) {
        byte[] data = new byte[content.readableBytes()];
        content.readBytes(data);
        MyContent myContent;
        try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));){
            myContent = (MyContent) ois.readObject();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return myContent;
    }
}
